package com.bq.gametrade.ui.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.base.BaseActivity;
import com.bq.gametrade.bean.BankCardList;
import com.bq.gametrade.bean.BankCardListDetails;
import com.bq.gametrade.bean.ResponseBean;
import com.bq.gametrade.bean.UserInfoDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.service.SmsReceiver;
import com.bq.gametrade.ui.dialog.LoadingProgressDialog;
import com.bq.gametrade.utils.DateUtils;
import com.bq.gametrade.utils.MD5Util;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.view.BankAccountListSpinner;
import com.bq.gametrade.view.PayPasswordValidationView;
import com.bq.gametrade.view.TimeButton;
import com.bq.gametrade.view.popwindow.BankCardListPop;
import com.bq.gametrade.widget.PromptAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class WithdrawalActivity extends BaseActivity implements View.OnClickListener{

    private BankAccountListSpinner sp_banks;
    private ImageView back;
    private TextView tvTitle,leftText;
    private ArrayList<BankCardListDetails> bankCardLists = new ArrayList<>();
    private EditText etWithdrawalMoney,etCode;
    private TextView tvBalanceMoney,tvAllWithdrawal,tvGetCode,tvMyPhoneNumber;
    private String money;
    private Button btnOk;
    private TextView tvBankCard;

    private String bnkCardId;
    private SmsReceiver smsReceiver;
    private LoadingProgressDialog progressDialog;
    private UserInfoDetails userInfo;

    //提现提醒
    private LinearLayout layRemindOne;
    private LinearLayout layNoRemind,layRemind;
    private TextView tvWithdrawalMinOne,tvWithdrawalMaxOne;
    private TextView tvWithdrawalCount,tvWithdrawalMin,tvWithdrawalMax,tvNormalPoundage;
    private TextView tvMinPoundageOne,tvMinPoundageTwo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdrawal);
        progressDialog = new LoadingProgressDialog(this,"正在提现···");
        if(application.isLogin()){
            userInfo = application.getUserInfo();
        }else {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        }
        getWithdrawalInstruction();
        initView();
        readSms();


    }

    @Override
    protected void performHandleMessage(Message msg) {
        super.performHandleMessage(msg);
        if (msg.what == 1)
        {
            etCode.setText(msg.obj.toString());
        }
    }

    private void readSms(){
        smsReceiver = new SmsReceiver(WithdrawalActivity.this,mHandler);
        IntentFilter  filter = new IntentFilter();
        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(smsReceiver,filter);
    }


    @Override
    protected void onResume() {
        super.onResume();
        getBankCardList();

    }

    private void initView() {
        back = serchViewById(R.id.image_back);
        back.setOnClickListener(this);
        tvTitle = serchViewById(R.id.title_name);
        tvTitle.setText("提现");
        leftText = serchViewById(R.id.title_leftText);
        leftText.setText("账单");
        leftText.setVisibility(View.VISIBLE);
        leftText.setOnClickListener(this);
        sp_banks = serchViewById(R.id.sp_banks);
        sp_banks.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bankCardLists.size()>0){
                    sp_banks.showWindow();
                }else {
                    getBankCardList();
                }

            }
        });
        sp_banks.setOnSpinnerItemClickListener(new BankAccountListSpinner.OnSpinnerItemClickListener() {
            @Override
            public void OnSpinnerItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
        tvBankCard = serchViewById(R.id.tv_banCard);
        tvBankCard.setOnClickListener(this);
        etWithdrawalMoney = serchViewById(R.id.et_withdrawalMoney);
        etWithdrawalMoney.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);

        etWithdrawalMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        etWithdrawalMoney.setText(s);
                        etWithdrawalMoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etWithdrawalMoney.setText(s);
                    etWithdrawalMoney.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etWithdrawalMoney.setText(s.subSequence(0, 1));
                        etWithdrawalMoney.setSelection(1);
                        return;
                    }
                }
                if(etWithdrawalMoney.getText().toString().equals("")){
                    money = "0";
                }else {
                    money = etWithdrawalMoney.getText().toString();
                }
                if(Double.parseDouble(money)>Double.parseDouble(application.getUserInfo().userMoney)){
                    tvBalanceMoney.setText("您的提现金额已超过余额");
                    tvBalanceMoney.setTextColor(getResources().getColor(R.color.red));
                }else {
                    tvBalanceMoney.setText("可用余额  "+application.getUserInfo().userMoney+"元");
                    tvBalanceMoney.setTextColor(getResources().getColor(R.color.color666666));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {


            }
        });
        tvBalanceMoney = serchViewById(R.id.tv_accountBalanceMoney);
        tvBalanceMoney.setText("可用余额  "+application.getUserInfo().userMoney+"元");
        tvAllWithdrawal = serchViewById(R.id.tv_allWithdrawal);
        tvAllWithdrawal.setOnClickListener(this);
        btnOk = serchViewById(R.id.btn_confirm);
        btnOk.setOnClickListener(this);
        tvGetCode = serchViewById(R.id.tv_getCode);
        tvGetCode.setOnClickListener(this);
        etCode = serchViewById(R.id.et_code);
        tvMyPhoneNumber = serchViewById(R.id.tv_MyPhoneNumber);
        StringBuilder msg = new StringBuilder().append(userInfo.telNum.substring(0, 3))
                .append("****").append(userInfo.telNum.substring(7));
        tvMyPhoneNumber.setText(msg);


        layRemindOne = serchViewById(R.id.lay_remindOne);
        layNoRemind = serchViewById(R.id.lay_NoRemind);
        layRemind = serchViewById(R.id.lay_remind);
        tvWithdrawalCount = serchViewById(R.id.tv_allWithdrawalCount);
        tvWithdrawalMin = serchViewById(R.id.tv_withdrawalMin);
        tvWithdrawalMax = serchViewById(R.id.tv_withdrawalMax);
        tvNormalPoundage = serchViewById(R.id.tv_normalPoundage);
        tvMinPoundageOne = serchViewById(R.id.tv_minPoundageOne);
        tvMinPoundageTwo = serchViewById(R.id.tv_minPoundageTuo);
        tvWithdrawalMinOne = serchViewById(R.id.tv_withdrawalMinOne);
        tvWithdrawalMaxOne = serchViewById(R.id.tv_withdrawalMaxOne);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(smsReceiver != null){
            unregisterReceiver(smsReceiver);
        }
    }

    private boolean isShowPop = true;
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_banCard:
                if(bankCardLists.size()<=0){
                    new PromptAlertDialog(WithdrawalActivity.this).builder().setTitle("提示").setTouchOutsideCanceled(false)
                            .setCancelable(false)
                            .setMsg("您还没有绑定银行卡不能提现？现在去绑定")
                            .setPositiveButton("绑卡", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    startActivity(new Intent(WithdrawalActivity.this, BankCardAddActivity.class));
                                }
                            }).setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    }).show();
                    return;
                }
                String bankCard4 = tvBankCard.getText().toString().substring(tvBankCard.getText().toString().length()-4,tvBankCard.getText().toString().length());
                BankCardListPop pop = new BankCardListPop(WithdrawalActivity.this,bankCardLists,bankCard4);
                isShowPop = !tvBankCard.isSelected();
                if(!isShowPop){
                    tvBankCard.setSelected(false);
                    pop.dismiss();
                }else {
                    tvBankCard.setSelected(true);
                    pop.showAsDropDown(tvBankCard);
                }
               pop.setBankCardNoListener(new BankCardListPop.OnGetBankCardNoListener() {
                   @Override
                   public void getBankCardNo(int position) {
                       bnkCardId = bankCardLists.get(position).id;
                       tvBankCard.setText(bankCardLists.get(position).bank_name
                               +"*"+bankCardLists.get(position).card_num.substring(bankCardLists.get(position).card_num.length()-4,bankCardLists.get(position).card_num.length()));
                   }
               });
                break;
            case R.id.image_back:
                finish();
                break;
            case R.id.tv_getCode:
                sendCode();
                break;
            case R.id.title_leftText:
                startActivity(new Intent(WithdrawalActivity.this,WithdrawalRecordsActivity.class));
                break;
            case R.id.tv_allWithdrawal:
               etWithdrawalMoney.setText(application.getUserInfo().userMoney);
                break;
            case R.id.btn_confirm:


                if(TextUtils.isEmpty(tvBankCard.getText().toString())){
                    toastShow("您还没有选择要体现的银行卡");
                    return;
                }
                if(etWithdrawalMoney.getText().toString().equals("")){
                    toastShow("提现金额未填写");
                    return;
                }
                if(Double.valueOf(etWithdrawalMoney.getText().toString())>Double.valueOf(userInfo.userMoney)){
                    toastShow("您没有这么多余额了");
                    return;
                }
//                if(!TextUtils.isEmpty(etWithdrawalMoney.getText().toString())){
//                    DecimalFormat df = new DecimalFormat("######0.00");
//
//                    double cuont = Double.parseDouble(etWithdrawalMoney.getText().toString().replace(" ",""))*0.05;
//                    new PromptAlertDialog(WithdrawalActivity.this).builder().setTitle("友情提示").setTouchOutsideCanceled(true)
//                            .setMsg("您本次提现将收取"+df.format(cuont)+"元的手续费")
//                            .setPositiveButton("确定", new View.OnClickListener() {
//                                @Override
//                                public void onClick(View v) {
//
//                                }
//                            }).setNegativeButton("取消", new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//                        }
//                    }).show();
//                }
//                if((Double.parseDouble(etWithdrawalMoney.getText().toString())+1.00)>Double.parseDouble(application.getUserInfo().userMoney)){
//                    toastShow("账户余额不足以支付提现手续费");
//                    return;
//                }
                if(TextUtils.isEmpty(etCode.getText().toString())){
                    toastShow("验证码未填写");
                    return;
                }

                if(!NetworkUtils.isNetworkAvailable(WithdrawalActivity.this)){
                    toastShow("网络异常");
                    return;
                }
                toPay();
                break;
        }
    }


    /**
     * 获取绑定银行卡列表
     */
    private void getBankCardList() {
        Map<String, String> params = new HashMap<>();
        params.put("token",application.getUserInfo().token);
        showSpotsDialog();
        VRHttp.geBindBankcardList(WithdrawalActivity.this, HttpLink.GET_BANKCARD_LIST_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();
                if(response != null){
                    BankCardList bankCardList = (BankCardList) response;
                    bankCardLists = bankCardList.card_list;
                    if(bankCardList.status.equals("0")){
                        if(bankCardLists.size()>0){
//                            sp_banks.init(WithdrawalActivity.this,bankCardLists);
                            bnkCardId = bankCardLists.get(0).id;
                            tvBankCard.setText(bankCardLists.get(0).bank_name
                                    +"*"+bankCardLists.get(0).card_num.substring(bankCardLists.get(0).card_num.length()-4,bankCardLists.get(0).card_num.length()));
                        }else {
                            new PromptAlertDialog(WithdrawalActivity.this).builder().setTitle("提示")
                                    .setTouchOutsideCanceled(false)
                                    .setCancelable(false)
                                    .setMsg("您还没有绑定银行卡不能提现？现在去绑定")
                                    .setPositiveButton("绑定", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            startActivity(new Intent(WithdrawalActivity.this, BankCardAddActivity.class));
                                        }
                                    }).setNegativeButton("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    finish();
                                }
                            }).show();
                        }
                    }else {
                        toastShow("登录超时，请重新登陆");
                        application.setUserInfo(null);
                        startActivity(new Intent(WithdrawalActivity.this,LoginActivity.class));
                        finish();
                    }

                }
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                closeSpotsDialog();
                toastShow("获取银行卡信息失败");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }
        });
    }


    /**
     * 验证支付密码-----start
     */

    private void toPay() {
        final PayPasswordValidationView payPasswordValidationView = new PayPasswordValidationView(WithdrawalActivity.this, userInfo, progressDialog);
        payPasswordValidationView.showAtLocation(WithdrawalActivity.this.findViewById(R.id.activity_withdrawal),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        payPasswordValidationView.backgroundAlpha(0.6f);
        payPasswordValidationView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                payPasswordValidationView.backgroundAlpha(1f);
            }
        });

        payPasswordValidationView.setOnFinishInputPayPassword(new PayPasswordValidationView.OnPayPasswordInputFinish() {
            @Override
            public void inputFinish(String status) {
                if (status.equals("0")) {
                    withdrawal();
                }
            }
        });
    }

    /**
     * end
     **/

    private void closeDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private void getWithdrawalInstruction(){
        VRHttp.getResponse(WithdrawalActivity.this, HttpLink.WITHDRAWAL_INSTRUCTION, null, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {

                try {
                    JSONObject object = new JSONObject(response.toString());
                    //是否收取手续费
                    String isShargePoundage = object.getString("PAY_FEE_OPEN");
                    if(isShargePoundage.equals("1")){
                        layNoRemind.setVisibility(View.VISIBLE);
                        layRemind.setVisibility(View.GONE);
                    }else if(isShargePoundage.equals("0")) {
                        layNoRemind.setVisibility(View.GONE);
                        layRemind.setVisibility(View.VISIBLE);
                    }
                    if(isShargePoundage.equals("1")){
                        //当前提现次数
                        String todayWithdrawalNum = object.getString("PAY_CASH_COUNT");
                        tvWithdrawalCount.setText(todayWithdrawalNum);
                        //单次最少提取金额
                        String singleMinMoney = object.getString("PAY_CASH_MIN_MONEY");
                        tvWithdrawalMin.setText(singleMinMoney);
                        tvWithdrawalMinOne.setText(singleMinMoney);
                        //单次最大提取金额
                        String singleMaxMoney = object.getString("PAY_CASH_MAX_MONEY");
                        tvWithdrawalMax.setText(singleMaxMoney);
                        tvWithdrawalMaxOne.setText(singleMaxMoney);
                        //单笔最小手续费
                        String singleMinPoundage = object.getString("PAY_FEE_DEFAULT");
                        tvNormalPoundage.setText(singleMinPoundage);
                        //单笔最大手续费
                        String singleMaxPoundage = object.getString("PAY_FEE_DEFAULT");
                        tvMinPoundageTwo.setText(singleMaxPoundage);
                    }


                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * end
     **/

    private void sendCode(){
        /**
         * 注册时验证码类型：codeType = 0;
         */
        String codeType = "1";
        Map<String,String> params = new HashMap<>();
        params.put("tel",userInfo.telNum);
        params.put("codeType",codeType);
        showSpotsDialog("正在发送验证码···");
        VRHttp.sendRequest(WithdrawalActivity.this, HttpLink.GET_VERIFICATIONCODE_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                closeSpotsDialog();

                if (response != null) {
                    ResponseBean bean = (ResponseBean) response;
                    if (bean.status.equals("0")) {
                        toastShow("已发送！请查看");
                        etCode.requestFocus();
                        TimeButton timeButton = new TimeButton(WithdrawalActivity.this, 60 * 1000, 1000, tvGetCode);
                        timeButton.start();
                    }
                } else {
                    toastShow("获取验证码失败");
                }
            }
            @Override
            public void onError(String error) {
                super.onError(error);
                toastShow("发送验证码失败");
                closeSpotsDialog();
            }
        });
    }


    private void withdrawal(){
        Map<String,String> params = new HashMap<>();
        params.put("token",userInfo.token);
        params.put("code",etCode.getText().toString());
        params.put("account",application.getUserInfo().account);
        params.put("money",etWithdrawalMoney.getText().toString());
        params.put("bank_id",bnkCardId);
        params.put("cashId", MD5Util.md5(DateUtils.getTimestamp()+userInfo.account+"android"));
        showSpotsDialog();
        VRHttp.getResponse(WithdrawalActivity.this, HttpLink.WITHDRAWAL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                try {
                    JSONObject object = new JSONObject(response.toString());
                    String status = object.getString("status");
                    if(status.equals("0")){
                        toastShow("提现申请已提交，请耐心等待");
                        finish();
                    }else if(status.equals("1")){
                        toastShow("今日提现次数不足");
                    }
                    else if (status.equals("99")) {
                        toastShow("登录超时");
                        application.setUserInfo(null);
                        startActivity(new Intent(WithdrawalActivity.this, LoginActivity.class));
                        finish();
                    } else if (status.equals("98")) {
                        toastShow("您的账号已在其它设备登录，请重新登录修改您的密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(WithdrawalActivity.this, LoginActivity.class));
                        finish();
                    }else{
                        String message = object.getString("msg");
                        toastShow(new String(Base64.decode(message.getBytes(), 0, message.length(), Base64.DEFAULT)));
                    }

                }catch (JSONException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeDialog();
            }
        });
    }
}
